/**
 * @projectName demo-master
 * @fileName NacosConfig.java
 * @packageName org.example.provider.config
 * @author xaoyaoyao
 * @date 2021/3/30 09:56
 * @version V1.0
 * @copyright (c) 2021, xaoyaoyao@aliyun.com All Rights Reserved.
 */
package org.example.provider.config;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author xaoyaoyao
 * @className NacosConfig
 * @description
 * @date 2021/3/30 09:56
 */
@Slf4j
@Configuration
public class NacosConfig {

	@Resource
	private SysCommonConfig sysCommonConfig;

	@NacosInjected
	private NamingService namingService;

	@Value("${server.port}")
	private int serverPort;

	@Value("${spring.application.name}")
	private String applicationName;

	@PostConstruct
	public void registerInstance() throws NacosException {
		namingService.registerInstance(applicationName, sysCommonConfig.getNacosServerAddr(), serverPort);
		namingService.subscribe("nacos-provider", new EventListener() {
			@Override
			public void onEvent(Event event) {
				log.debug("获取注册的服务名=>{}", ((NamingEvent) event).getServiceName());
				log.debug("获取注册的服务实例=>{}", ((NamingEvent) event).getInstances());
			}
		});
	}

}
